<template>
	<view class="page groups-page">
		<!-- 自定义导航栏 -->
		<br>
		<ob-navbar title="群聊管理" :show-back="true" />
		<br>
		
		<view class="content">
			<!-- 创建群聊入口 -->
			<view class="create-section">
				<view class="create-option" @click="createGroup">
					<view class="option-icon">C</view>
					<view class="option-info">
						<text class="option-title">创建群聊</text>
						<text class="option-desc">发起群聊，邀请好友加入</text>
					</view>
					<text class="option-arrow">></text>
				</view>
				
				<view class="create-option" @click="joinGroup">
					<view class="option-icon">J</view>
					<view class="option-info">
						<text class="option-title">搜索群聊</text>
						<text class="option-desc">通过群号或邀请码加入群聊</text>
					</view>
					<text class="option-arrow">></text>
				</view>
			</view>
			
			<!-- 搜索框 -->
			<view class="search-section">
				<view class="search-box">
					<text class="search-icon">S</text>
					<input 
						v-model="searchKeyword"
						type="text" 
						placeholder="搜索群聊"
						class="search-input"
						@input="onSearchInput"
					/>
					<text v-if="searchKeyword" class="clear-btn" @click="clearSearch">×</text>
				</view>
			</view>
			
			<!-- 群聊列表 -->
			<view class="groups-section">
				<view class="section-header">
					<text class="section-title">我的群聊 ({{ filteredGroups.length }})</text>
					<text class="manage-btn" @click="toggleManageMode">{{ isManageMode ? '完成' : '管理' }}</text>
				</view>
				
				<view class="groups-list">
					<view 
						v-for="group in filteredGroups" 
						:key="group.id"
						class="group-item"
						@click="openGroupChat(group)"
					>
						<view v-if="isManageMode" class="select-checkbox" @click.stop="toggleSelect(group)">
							<text class="checkbox-icon">{{ group.selected ? '✓' : '' }}</text>
						</view>
						
						<image 
							:src="getAvatar(group.avatar)"
							class="group-avatar" 
							mode="aspectFill" 
						/>
						
						<view class="group-info">
							<view class="group-header">
								<text class="group-name">{{ group.name }}</text>
								<text class="group-time">{{ formatTime(group.lastMessageTime) }}</text>
							</view>
							<view class="group-detail">
								<text class="group-desc">{{ group.memberCount }}人 · {{ group.lastMessage || '暂无消息' }}</text>
								<view v-if="group.unreadCount > 0" class="unread-badge">
									{{ group.unreadCount > 99 ? '99+' : group.unreadCount }}
								</view>
							</view>
						</view>
						
						<view class="group-status">
							<text v-if="group.isMuted" class="mute-icon">M</text>
							<text v-if="group.isOwner" class="owner-tag">群主</text>
							<text v-else-if="group.isAdmin" class="admin-tag">管理员</text>
						</view>
					</view>
				</view>
				
				<!-- 空状态 -->
				<view v-if="filteredGroups.length === 0" class="empty-state">
					<ob-empty 
						:image="'/static/images/empty-groups.png'"
						title="暂无群聊"
						description="创建或加入群聊开始交流吧"
					/>
					<button class="create-group-btn" @click="createGroup">创建群聊</button>
				</view>
			</view>
			
			<!-- 管理操作栏 -->
			<view v-if="isManageMode && selectedGroups.length > 0" class="manage-actions">
				<button class="action-btn mute" @click="batchMuteGroups">免打扰</button>
				<button class="action-btn exit" @click="batchExitGroups">退出群聊</button>
			</view>
		</view>
		
		<!-- 加载组件 -->
		<ob-loading :visible="isLoading" text="加载中..." />
	</view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import messageApi from '../../api/message.js'
import groupApi from '../../api/group.js'
import { formatDistanceToNow } from '../../utils/common.js'
import { resolveAvatarUrl } from '../../utils/avatar.js'

const getAvatar = (url) => resolveAvatarUrl(url || '')

// 响应式数据
const groups = ref([])
const searchKeyword = ref('')
const isLoading = ref(false)
const isManageMode = ref(false)

// 计算属性
const filteredGroups = computed(() => {
	if (!searchKeyword.value.trim()) {
		return groups.value
	}
	
	const keyword = searchKeyword.value.toLowerCase()
	return groups.value.filter(group => {
		const name = (group.name || '').toLowerCase()
		return name.includes(keyword)
	})
})

const selectedGroups = computed(() => {
	return groups.value.filter(group => group.selected)
})

// 生命周期
onMounted(() => {
	loadGroups()
})

// 方法
const loadGroups = async () => {
	try {
		isLoading.value = true
		const response = await groupApi.getMyGroups()
		groups.value = (response.list || []).map(group => ({
			...group,
			selected: false
		}))
	} catch (error) {
		console.error('加载群聊列表失败:', error)
		uni.showToast({
			title: '加载失败',
			icon: 'none'
		})
	} finally {
		isLoading.value = false
	}
}

const formatTime = (timestamp) => {
	if (!timestamp) return ''
	
	const now = new Date()
	const messageTime = new Date(timestamp)
	const diffInHours = (now - messageTime) / (1000 * 60 * 60)
	
	if (diffInHours < 24) {
		return messageTime.toLocaleTimeString('zh-CN', { 
			hour: '2-digit', 
			minute: '2-digit' 
		})
	} else if (diffInHours < 48) {
		return '昨天'
	} else {
		return messageTime.toLocaleDateString('zh-CN', { 
			month: '2-digit', 
			day: '2-digit' 
		})
	}
}

const onSearchInput = () => {
	// 实时搜索
}

const clearSearch = () => {
	searchKeyword.value = ''
}

const toggleManageMode = () => {
	isManageMode.value = !isManageMode.value
	if (!isManageMode.value) {
		// 退出管理模式，清除选择
		groups.value.forEach(group => {
			group.selected = false
		})
	}
}

const toggleSelect = (group) => {
	group.selected = !group.selected
}

const openGroupChat = (group) => {
	if (isManageMode.value) return
	
	uni.navigateTo({
		url: `/pages/message/chat?conversationId=${group.id}&type=group`
	})
}

const createGroup = () => {
	uni.navigateTo({
		url: '/pages/message/create-group'
	})
}

const joinGroup = () => {
	uni.navigateTo({
		url: '/pages/message/join-group'
	})
}

const batchMuteGroups = () => {
	if (selectedGroups.value.length === 0) return
	
	uni.showModal({
		title: '群聊免打扰',
		content: `确定要设置选中的${selectedGroups.value.length}个群聊为免打扰吗？`,
		success: async (res) => {
			if (res.confirm) {
				try {
					// 批量设置免打扰
					const mutePromises = selectedGroups.value.map(group => 
						messageApi.muteConversation(group.id, true)
					)
					await Promise.all(mutePromises)
					
					// 更新状态
					selectedGroups.value.forEach(group => {
						group.isMuted = true
						group.selected = false
					})
					
					uni.showToast({
						title: '设置成功',
						icon: 'success'
					})
				} catch (error) {
					console.error('设置免打扰失败:', error)
					uni.showToast({
						title: '设置失败',
						icon: 'none'
					})
				}
			}
		}
	})
}

const batchExitGroups = () => {
	if (selectedGroups.value.length === 0) return
	
	uni.showModal({
		title: '退出群聊',
		content: `确定要退出选中的${selectedGroups.value.length}个群聊吗？退出后将无法接收群消息。`,
		confirmText: '退出',
		cancelText: '取消',
		confirmColor: '#ff4757',
		success: async (res) => {
			if (res.confirm) {
				try {
					// 批量退出群聊
					const exitPromises = selectedGroups.value.map(group =>
						groupApi.leaveGroup(group.id)
					)
					await Promise.all(exitPromises)

					// 从列表中移除
					groups.value = groups.value.filter(group => !group.selected)
					
					uni.showToast({
						title: '退出成功',
						icon: 'success'
					})
				} catch (error) {
					console.error('退出群聊失败:', error)
					uni.showToast({
						title: '退出失败',
						icon: 'none'
					})
				}
			}
		}
	})
}
</script>

<style lang="scss" scoped>
.groups-page {
	background: #FAFAFA;
	min-height: 100vh;
}

.content {
	padding: 0;
}

.create-section {
	background: #FFFFFF;
	margin: 15px;
	border-radius: 8px;
	padding: 0 20px;
}

.create-option {
	display: flex;
	align-items: center;
	padding: 15px 0;
	border-bottom: 1px solid #F8F9FA;
	
	&:last-child {
		border-bottom: none;
	}
	
	&:active {
		background: #F8F9FA;
	}
}

.option-icon {
	width: 40px;
	height: 40px;
	background: #F8F9FA;
	border: 1px solid #E9ECEF;
	border-radius: 20px;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 16px;
	font-weight: 600;
	color: #6C757D;
	margin-right: 15px;
}

.option-info {
	flex: 1;
}

.option-title {
	font-size: 16px;
	color: #333333;
	font-weight: 500;
	display: block;
	margin-bottom: 4px;
}

.option-desc {
	font-size: 12px;
	color: #999999;
}

.option-arrow {
	font-size: 16px;
	color: #CED4DA;
}

.search-section {
	background: #FFFFFF;
	padding: 15px 20px;
	margin: 0 15px 15px;
	border-radius: 8px;
}

.search-box {
	position: relative;
	display: flex;
	align-items: center;
}

.search-icon {
	font-size: 14px;
	font-weight: 600;
	color: #6C757D;
	margin-right: 8px;
}

.search-input {
	flex: 1;
	background: #F8F9FA;
	border: 1px solid #E9ECEF;
	border-radius: 20px;
	padding: 8px 15px;
	font-size: 14px;
	height: 36px;
	box-sizing: border-box;
}

.clear-btn {
	position: absolute;
	right: 15px;
	font-size: 16px;
	color: #999999;
	width: 20px;
	text-align: center;
}

.groups-section {
	background: #FFFFFF;
	margin: 0 15px;
	border-radius: 8px;
	overflow: hidden;
}

.section-header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 15px 20px;
	border-bottom: 1px solid #F0F0F0;
}

.section-title {
	font-size: 16px;
	font-weight: 600;
	color: #333333;
}

.manage-btn {
	font-size: 14px;
	color: #495057;
}

.groups-list {
	padding: 0 20px;
}

.group-item {
	display: flex;
	align-items: center;
	padding: 15px 0;
	border-bottom: 1px solid #F8F9FA;
	
	&:last-child {
		border-bottom: none;
	}
	
	&:active {
		background: #F8F9FA;
	}
}

.select-checkbox {
	width: 20px;
	height: 20px;
	border: 1px solid #CED4DA;
	border-radius: 4px;
	display: flex;
	align-items: center;
	justify-content: center;
	margin-right: 12px;
	background: #FFFFFF;
}

.checkbox-icon {
	font-size: 12px;
	color: #495057;
}

.group-avatar {
	width: 50px;
	height: 50px;
	border-radius: 25px;
	margin-right: 12px;
}

.group-info {
	flex: 1;
	min-width: 0;
}

.group-header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	margin-bottom: 6px;
}

.group-name {
	font-size: 16px;
	font-weight: 500;
	color: #333333;
	flex: 1;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}

.group-time {
	font-size: 12px;
	color: #999999;
	flex-shrink: 0;
}

.group-detail {
	display: flex;
	align-items: center;
	justify-content: space-between;
}

.group-desc {
	font-size: 12px;
	color: #999999;
	flex: 1;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}

.unread-badge {
	background: #DC3545;
	color: #FFFFFF;
	font-size: 12px;
	padding: 2px 6px;
	border-radius: 10px;
	min-width: 18px;
	text-align: center;
	flex-shrink: 0;
	margin-left: 8px;
}

.group-status {
	display: flex;
	flex-direction: column;
	align-items: center;
	gap: 4px;
}

.mute-icon {
	font-size: 12px;
	color: #6C757D;
	background: #F8F9FA;
	border: 1px solid #E9ECEF;
	border-radius: 10px;
	padding: 2px 6px;
}

.owner-tag, .admin-tag {
	font-size: 10px;
	padding: 2px 6px;
	border-radius: 8px;
	background: #F8F9FA;
	color: #6C757D;
	border: 1px solid #E9ECEF;
}

.empty-state {
	padding: 50px 20px;
	text-align: center;
}

.create-group-btn {
	background: #495057;
	color: #FFFFFF;
	border: none;
	border-radius: 6px;
	padding: 12px 24px;
	font-size: 14px;
	margin-top: 20px;
}

.manage-actions {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	background: #FFFFFF;
	padding: 15px 20px;
	border-top: 1px solid #F0F0F0;
	display: flex;
	gap: 15px;
}

.action-btn {
	flex: 1;
	height: 44px;
	border: none;
	border-radius: 6px;
	font-size: 14px;
	
	&.mute {
		background: #F8F9FA;
		color: #495057;
		border: 1px solid #E9ECEF;
	}
	
	&.exit {
		background: #DC3545;
		color: #FFFFFF;
	}
}
</style>